package com.btpj.jetpack.base

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.paging.PagedList
import androidx.paging.PagedListAdapter
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.btpj.jetpack.R
import com.btpj.jetpack.databinding.LayoutBaseListBinding
import com.btpj.jetpack.utils.StatusBarUtil
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import kotlinx.android.synthetic.main.layout_base_list.*
import org.koin.androidx.viewmodel.ext.android.getViewModel
import kotlin.reflect.KClass

/**
 * 列表类Activity的基类
 *
 * @author LTP 2020/7/21
 */
abstract class BaseListActivity<T, VM : BaseListViewModel<T>> : AppCompatActivity(),
    OnRefreshLoadMoreListener {

    abstract fun initActionBar()
    abstract fun generateAdapter(): PagedListAdapter<T, RecyclerView.ViewHolder>

    val mAdapter by lazy { generateAdapter() }
    lateinit var mViewModel: VM
    lateinit var mBinding: LayoutBaseListBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        StatusBarUtil.setImmersionStatus(this)
        mBinding = DataBindingUtil.setContentView(this, R.layout.layout_base_list)
        initActionBar()

        val decoration = DividerItemDecoration(this, DividerItemDecoration.VERTICAL)
        decoration.setDrawable(ContextCompat.getDrawable(this, R.drawable.list_divier_home)!!)
        recyclerView.apply {
            layoutManager = LinearLayoutManager(this@BaseListActivity)
            addItemDecoration(decoration)
            adapter = mAdapter
        }

        smartRefreshLayout.apply {
            setEnableRefresh(true)
            setEnableLoadMore(true)
            setOnRefreshLoadMoreListener(this@BaseListActivity)
        }

        initViewModel()
    }

    private fun initViewModel() {
        mViewModel =
            getViewModel(this.javaClass.kotlin.supertypes[0].arguments[1].type!!.classifier!! as KClass<VM>)
//        mViewModel = ViewModelProvider(this).get(getListViewModelClazz(this))
        mViewModel.pageData.observe(this, Observer {
            submitPageList(it)
        })
    }

    fun submitPageList(pagedList: PagedList<T>) {
        mAdapter.submitList(pagedList)
    }

    fun finishRefresh() {
        val state = smartRefreshLayout.state
        if (state.isOpening) {
            if (state.isHeader) {
                smartRefreshLayout.finishRefresh()
            } else if (state.isFooter) {
                smartRefreshLayout.finishLoadMore()
            }
        }
    }
}